package com.xxwy.util;

import io.netty.util.concurrent.FastThreadLocal;

import java.util.concurrent.TimeUnit;

/**
 * Netty中有两个性能优化的工具类：
 * 其一：FastThreadLocal
 * @author wy
 * @date 2020/3/19 16:11
 */
public class FastThreadLocalTest {

  private static FastThreadLocal<Object> threadLocal = new FastThreadLocal<Object>(){
    @Override
    protected Object initialValue() throws Exception {
      return new Object();
    }
  };

  public static void main(String[] args) {

    new Thread(()->{
      //每个get如果没有set都调用了initiaValue()创建了新的值，
      // 所以两个线程中拿到的Object是不一样的
      //Returns the current value for the current thread
      Object o = threadLocal.get();
      System.out.println(o);//java.lang.Object@5bb2b40b
      while (true){
        threadLocal.set(new Object());
        try {
          TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }).start();

    new Thread(()->{
      Object o = threadLocal.get();
      System.out.println(o);//java.lang.Object@22dbaad9
      //上面的线程对threadLocal内值得修改和我没关系
      while (true){
        Object o1 = threadLocal.get();
        System.out.println(o1==o);//一直返回true
      }
    }).start();

  }

}
